package com.upcoming.data.storm.util;

import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 作者：tianjiayuan
 * 创建时间：2018-05-17 15:50
 * 类描述：
 * 修改人：
 * 修改时间：
 */
public class MyUtil {

    private static OutputStream os;
    static {
        try {
            Runtime runtime = Runtime.getRuntime();
            Process p = runtime.exec("nc 192.168.5.19 8888");
            os = p.getOutputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 输出日志到nc server
     * @param o
     */
    public static void outLog2NC(Object o, String msg) {
        try {
            String prefix = "";

            //取得系统时间
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm");
            String time = sdf.format(date);


            //host
            String host = InetAddress.getLocalHost().getHostName();


            //进程信息
            RuntimeMXBean r = ManagementFactory.getRuntimeMXBean();
            //8080@s1001
            String pId = r.getName().split("@")[0];

            //线程
            String tName = Thread.currentThread().getName();

            Long tId = Thread.currentThread().getId();

            String clzz = o.getClass().getSimpleName();

            Integer hashcode = o.hashCode();

            prefix = "[" + time + " " + host + " " + pId + " TID" + tId + " " + clzz + "@" + hashcode + "] " + msg + "\n";

            os.write(prefix.getBytes());
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static byte[] int2byte(int i) {
        byte[] arr = new byte[4];
        arr[0] = (byte)(i >>> 24);
        arr[1] = (byte)(i >>> 16);
        arr[2] = (byte)(i >>> 8);
        arr[3] = (byte)(i >>> 0);
        return arr;
    }

    public static int byte2int(byte[] arr) {
        return arr[0] << 24 | arr[1] << 16 | arr[2] << 8 | arr[3];
    }
}
